<?php
/** 
	*后台商品分类控制器类
	* 
	*
	* @author      3+1项目组.hzy
	* @version     2018-02-02 09:48
*/
namespace app\admin\controller;
use think\Controller;
use think\Db;
class Cate extends Allow
{
	//调整类别顺序
	public function getCates()
    {
    	//获取分类
    	$data=Db::query("select *,concat(path,',',id) as paths from goods_cates order by paths");
    	//遍历
    	foreach($data as $key=>$value){
    		//echo $value['path'].'<br>';
    		//转换为数组
    		$arr=explode(",",$value['path']);
    		//获取逗号个数
    		$len=count($arr)-1;
    		//字符串重复函数
    		$data[$key]['name']=str_repeat("---|",$len).$value['name'];
    	}
       return $data;
    }
	//列表
	public function getIndex()
    {
    	//获取分类
    	$cate=$this->getcates();
       return $this->fetch('Cate/index',['cate'=>$cate]);
    }
	//加载添加模块
    public function getAdd()
    {
    	//获取所有分类信息
    	$cate=Db::table("goods_cates")->select();
       return $this->fetch('Cate/add',['cate'=>$cate]);
    }
    //执行添加
    public function postInsert()
    {
    	//创建请求对象
    	$request=request();
    	$data=$request->only(['name','pid']);
    	//获取pid
    	$pid=$request->param('pid');
    	//添加顶级分类
    	if($pid==0){
    		//拼接path
    		$data['path']='0';
    		// echo "<pre>";
    		// var_dump($data);
    	}else{
    		//获取父类信息
    		$info=Db::table("goods_cates")->where('id',$pid)->find();
    		//拼接path
    		$data['path']=$info['path'].",".$info['id'];
    	}
    	//插入数据库
    	if(Db::table("goods_cates")->insert($data)){
    		//echo 1;
            $this->success('添加成功','/cate/index');
    	}else{
    		//echo "error";
            $this->error('添加失败');
    	}
    }
    //执行删除
    public function getDelete()
    {
        $request=request();
        //获取id
        $id=$request->param('id');
        // 根据id查询出有没有子类
        $data=Db::table('goods_cates')->where('pid',$id)->select();
        // echo '<pre>';
        // var_dump($data);
        if($data){
            // 有子类
            $this->error('有子类,不能删除','/cate/index');
        }
        $datas=Db::table('goods_cates')->where('id',$id)->delete();
        if($datas){
            $this->success('删除成功','/cate/index');
        }else{
             $this->error('有子类,不能删除','/cate/index');
        }
    }
    //执行修改
    public function getEdit()
    {
        $request=request();
        //获取id
        $id=$request->param('id');
        $data=Db::table('goods_cates')->select();
        $info=Db::table('goods_cates')->where('id',$id)->find();
        return $this->fetch('Cate/edit',['info'=>$info,'data'=>$data]);
    }
    //执行修改
    public function postUpdate(){
        $request=request();
        $id=$request->param('id');
        $data=$request->only(['name']);
        if(Db::table("goods_cates")->where("id",$id)->update($data)){
            $this->success("修改成功","/cate/index");
        }else{
            $this->error("修改失败");
        }
    }
}
